package com.example.guiguiapplicatio.fragment.followup;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.example.guiguiapplicatio.api.Entity.FollowUp;
import com.example.guiguiapplicatio.api.Interface.Api;
import com.example.guiguiapplicatio.R;
import com.example.guiguiapplicatio.databinding.FragmentFollowUpReportNewChildBinding;
import com.example.guiguiapplicatio.databindingBean.Followupnewchild;
import com.example.guiguiapplicatio.databindingBean.followup.FollowupWith;
import com.example.guiguiapplicatio.databindingBean.followup.ListFollowupWith;
import com.example.guiguiapplicatio.util.ResponseBody;
import com.example.guiguiapplicatio.utils.JsonUtil;
import com.example.guiguiapplicatio.utils.PreferencesUtil;
import com.example.guiguiapplicatio.utils.ToastUtil;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class FollowUpReportNewChildFragment extends Fragment {

    private ListFollowupWith listFollowupWith;
    private FollowupWith followupWith;
    private FollowUp followUp;
    private Retrofit retrofit;
    private Followupnewchild followupnewchild;
    private Api api;
    private int doctorId;
    private FragmentFollowUpReportNewChildBinding binding;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // retrofit2初始化
        OkHttpClient client = new OkHttpClient.Builder().
//                 readTimeout(30, TimeUnit.SECONDS).
//                writeTimeout(30, TimeUnit.SECONDS).
        connectTimeout(6, TimeUnit.SECONDS).build();//用于设置请求超时等限制时间

        retrofit = new Retrofit.Builder()
                .baseUrl(getString(R.string.api))
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        api = retrofit.create(Api.class);
        // retrofit2初始化
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentFollowUpReportNewChildBinding.inflate(inflater, container, false);
        // Inflate the layout for this fragment
        initData();
        setSelectBtn();
        setBtn();
        setBack();

        return binding.getRoot();
    }

    private void setEditWall() {
        binding.editWall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getContext()!=null){
                    ToastUtil.showToast(getContext(), "非该随访医师不可编辑！");
                }
            }
        });

        if (!followUp.getDoctorId().equals(doctorId)){
            binding.editWall.setVisibility(View.VISIBLE);
        }
    }

    private void setBack() {
        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().onBackPressed();
            }
        });
    }

    private void setSelectBtn() {
        binding.selectWayLayout.setVisibility(View.GONE);
        binding.selectWayBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (binding.selectWayLayout.getVisibility() == View.VISIBLE) {
                    binding.selectWayLayout.setVisibility(View.GONE);
                } else {
                    binding.selectWayLayout.setVisibility(View.VISIBLE);
                }
            }
        });

        if (followUp.getState()==2){
            binding.delete.setVisibility(View.VISIBLE);
            binding.updata.setVisibility(View.GONE);
            binding.invalidated.setVisibility(View.GONE);
        }else {
            binding.delete.setVisibility(View.GONE);
        }


    }

    private void setBtn() {
        binding.delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.selectWayLayout.setVisibility(View.GONE);

                AlertDialog aldg;
                AlertDialog.Builder adBd = new AlertDialog.Builder(getContext());
                adBd.setTitle("确定要删除？此举不可逆！");

                adBd.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        Call<ResponseBody<Object>> call = api.deleteFollowUp(followupWith);
                        call.clone().enqueue(new Callback<ResponseBody<Object>>() {
                            @Override
                            public void onResponse(Call<ResponseBody<Object>> call, Response<ResponseBody<Object>> response) {
                                ResponseBody<Object> responseBody = response.body();
                                if (responseBody.getMsg().length() > 0) {
                                    if (getContext() != null) {
                                        Toast.makeText(getContext(), responseBody.getMsg(), Toast.LENGTH_LONG).show();
                                        getActivity().onBackPressed();
                                    }
                                }else {
                                    if (getContext() != null) {
                                        Toast.makeText(getContext(), "删除失败", Toast.LENGTH_LONG).show();
                                        getActivity().onBackPressed();
                                    }
                                }
                            }

                            @Override
                            public void onFailure(Call<ResponseBody<Object>> call, Throwable t) {
                                if (getContext() != null) {
                                    Toast.makeText(getContext(), "网络连接有误", Toast.LENGTH_LONG).show();
                                    getActivity().onBackPressed();
                                }
                            }
                        });
                    }
                });
                adBd.setNegativeButton("取消", null);
                aldg = adBd.create();
                aldg.show();

            }
        });
        binding.updata.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.selectWayLayout.setVisibility(View.GONE);

                AlertDialog aldg;
                AlertDialog.Builder adBd = new AlertDialog.Builder(getContext());
                adBd.setTitle("是否跳转至修改页面");
                adBd.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Bundle bundle=new Bundle();
                        bundle.putSerializable("ListFollowupWith",listFollowupWith);
                        bundle.putBoolean("IS_EXIST_FOLLOWUP_TO_THIS",true);
                        bundle.putBoolean("IS_FOLLOWUP_TO_REPORT_THIS",true);
                        NavController navController= Navigation.findNavController(binding.getRoot());
                        navController.navigate(R.id.action_followUpReportNewChildFragment_to_newChildFragment,bundle);   //代码复用注意修改！！！
                    }
                });
                adBd.setNegativeButton("取消", null);
                aldg = adBd.create();
                aldg.show();
            }
        });

        binding.invalidated.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.selectWayLayout.setVisibility(View.GONE);

                AlertDialog aldg;
                AlertDialog.Builder adBd = new AlertDialog.Builder(getContext());
                adBd.setTitle("确定要作废？");

                adBd.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        followupWith.getFollow().setState(2);
                        Call<ResponseBody<Object>> call = api.updateFollowUp(followupWith);
                        call.clone().enqueue(new Callback<ResponseBody<Object>>() {
                            @Override
                            public void onResponse(Call<ResponseBody<Object>> call, Response<ResponseBody<Object>> response) {
                                ResponseBody<Object> responseBody = response.body();
                                if (responseBody.getMsg().length() > 0) {
                                    if (getContext() != null) {
                                        Toast.makeText(getContext(), "已作废", Toast.LENGTH_LONG).show();
                                        getActivity().onBackPressed();
                                    }
                                }
                            }

                            @Override
                            public void onFailure(Call<ResponseBody<Object>> call, Throwable t) {
                                if (getContext() != null) {
                                    Toast.makeText(getContext(), "网络连接有误", Toast.LENGTH_LONG).show();
                                    getActivity().onBackPressed();
                                }
                            }
                        });
                    }
                });
                adBd.setNegativeButton("取消", null);
                aldg = adBd.create();
                aldg.show();

            }
        });
    }

    private void initData() {
        listFollowupWith = (ListFollowupWith) getArguments().getSerializable("ListFollowupWith");
        doctorId= PreferencesUtil.getInt(getContext(),"doctor_id");

        if (listFollowupWith == null) {
            getActivity().onBackPressed();
        }

        followUp = listFollowupWith.getFollowUp();

        binding.setFollowupWith(listFollowupWith);

        Call<ResponseBody<FollowupWith>> call = api.getOneFollowupWith(followUp.getId());
        call.clone().enqueue(new Callback<ResponseBody<FollowupWith>>() {
            @Override
            public void onResponse(Call<ResponseBody<FollowupWith>> call, Response<ResponseBody<FollowupWith>> response) {
                ResponseBody<FollowupWith> responseBody = response.body();
                if (!responseBody.equals(null)) {
                    if (responseBody.getMsg().equals("无数据")) {

                        if (getContext() != null) {
                            Toast.makeText(getContext(), "错误!无数据", Toast.LENGTH_LONG).show();
                            getActivity().onBackPressed();
                        }
                    } else {

                        if (responseBody.getData()!=null){
                            //类型转换
                            String json = JsonUtil.toJson(responseBody.getData().getObject());                   //代码复用注意修改！！！
                            followupnewchild = JsonUtil.fromJson(json, Followupnewchild.class);
                            //类型转换
                            binding.setChild(followupnewchild);
                            if (followupnewchild.getSex() == null || followupnewchild.getSex().equals("")) {
                                binding.sex.setText(listFollowupWith.getSex());
                            } else {
                                binding.sex.setText(followupnewchild.getSex());
                            }
                            followupWith = responseBody.getData();

                            setEditWall();
                        }else {
                            if (getContext() != null) {
                                Toast.makeText(getContext(), "错误!无数据", Toast.LENGTH_LONG).show();
                                getActivity().onBackPressed();
                            }
                        }

                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody<FollowupWith>> call, Throwable t) {
                if (getContext() != null) {
                    Toast.makeText(getContext(), "网络连接有误", Toast.LENGTH_LONG).show();
                    getActivity().onBackPressed();
                }
            }
        });
    }
    @Override
    public void onResume() {
        BottomNavigationView bottomNavigationView = requireActivity().findViewById(R.id.nav_view);
        bottomNavigationView.setVisibility(View.INVISIBLE);
        //这两行代码设置隐藏底部导航栏，若要显示啧修改INVISIBLE为Visible（可见）
        super.onResume();
    }
}